package com.interauto.service.alarm;

import com.alibaba.fastjson.JSONObject;
import com.interauto.Dao.entity.Runtasktable;
import com.interauto.bean.AutoAlarmBean;
import com.interauto.bean.AutoAssertInfoBean;
import com.interauto.bean.AutoInterCaseBean;
import com.interauto.service.kaklis.RunTaskProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 处理告警相关的逻辑
 */
@Component
public class AutoAlarmService {
    private static final Logger logger= LoggerFactory.getLogger(AutoAlarmService.class);

    @Autowired
    private RunTaskProducer runTaskProducer;
    /**
     * 报警详情的url
     */
    @Value("${autointer.autourl}")
    private String alarmurl;

    public void goalarm(AutoInterCaseBean autoInterCaseBean, Runtasktable runtasktable,
                        AutoAssertInfoBean autoAssertInfoBean,int interrtid){
        if(autoAssertInfoBean == null || autoAssertInfoBean.getCodetype()<1){
            logger.info("this run is ok; interrtid is :"+interrtid);
            return;
        }
        if(runtasktable == null){
            logger.info("goalarm runtasktable is null;");
            return;
        }
        if(interrtid<1){
            logger.error("run auto add interrtid is fail;autoInterCaseBean is-->"+autoInterCaseBean.toString());
        }
        AutoAlarmBean autoAlarmBean=new AutoAlarmBean();
        autoAlarmBean.setAlarmtopic("");
        autoAlarmBean.setAlarmtime(new Date());
        autoAlarmBean.setCallemail(runtasktable.getCallemail());
        autoAlarmBean.setCallnumber(runtasktable.getCallnumber());
        String intername=autoInterCaseBean.getInterfacename();
        String errormessage=autoAssertInfoBean.getErrormessage();
        autoAlarmBean.setAlarmmessage(getalarmmessage(intername,errormessage));
        autoAlarmBean.setAlarmurl(getalarmurl(runtasktable.getProjectid(),interrtid));
        try{
            String alarmjson= JSONObject.toJSONString(autoAlarmBean);
            runTaskProducer.addautoalarm(alarmjson);
        }
        catch (Exception e){
            logger.error("send kafka alarm message is system error;autoAlarmBean is--->"+autoAlarmBean.toString());
        }

    }


    private String getalarmmessage(String intername,String errormessage){
        return String.format("接口名:%s;运行不通过!原因:%s;",intername,errormessage);
    }

    private String getalarmurl(int projectid,int interrtid){
        return String.format(alarmurl,projectid,interrtid);
    }
}
